package wpp.view;

import java.io.File;

import wpp.WPP;
import wpp.WPPConfig;
import wpp.cfg.WPFileBean;
import wpp.fxservice.DownloadFileService;
import wpp.util.OSUtil;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Tooltip;
import javafx.scene.effect.Reflection;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;

public class SimpleImageView extends ImageView {
	
	public static final String STYLE_NAME = "preview-imageview";
	
	private WPFileBean wpFileBean;
	
	public SimpleImageView(WPFileBean bean) {
		Image image = new Image(WPPConfig.getWPPreviewFile(bean.getFileName()).toURI().toString()
				, WPPConfig.getWpPreviewWidth(), WPPConfig.getWpPreviewHeight(), false, true);
		this.setImage(image);
		this.wpFileBean = bean;
		this.getStyleClass().add(STYLE_NAME);
		this.setOnMouseClicked(eventOnImageClicked());
		Reflection reflection = new Reflection();
		reflection.setFraction(0.3);
		this.setEffect(reflection);		
		Tooltip.install(this, new Tooltip(bean.getTitle()));
	}

	public WPFileBean getWpFileBean() {
		return wpFileBean;
	}
	
	private EventHandler<MouseEvent> eventOnImageClicked() {
		return new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent arg0) {
				WPFileBean bean = getWpFileBean();	
				bean.favor();
				final File iamge = new File(WPPConfig.getWpFilePath(bean.getFileName()));				
				DownloadFileService service = new DownloadFileService(bean.getWpURLPath(), iamge, false);
				EventHandler<WorkerStateEvent> eventHandler = new EventHandler<WorkerStateEvent>() {
					@Override
					public void handle(WorkerStateEvent arg0) {
						OSUtil.getInstance().changeWallpaper(iamge.getAbsolutePath());		
						WPP.clearProgressBar();
					}
				};				
				service.setOnSucceeded(eventHandler);
				WPP.showProgressBar(service.progressProperty());
				service.start();					
			}
		};
	}
	
}
